//
//  WDLocationManager.m
//  wd-serviceapp
//
//  Created by Bin Tang on 2024/8/27.
//

#import "WDLocationManager.h"

@interface WDLocationManager () <AMapLocationManagerDelegate, AMapSearchDelegate>

// 获得地址
@property (nonatomic, strong) AMapLocationManager *locationManager;

@property (nonatomic, strong) AMapSearchAPI *searchManager;

/// 根据地址搜索经纬度
@property (nonatomic, copy) void(^searchLocationBlock)(CGFloat latitude, CGFloat longitude);

/// 根据经纬度获取地址
@property (nonatomic, copy) void(^searchLocationLatLonBlock)(NSString *ads);

/// 得到两个经纬度的距离
@property (nonatomic, copy) void(^searchDistanceBlock)(NSInteger distance);

@property (nonatomic, assign) BOOL isStart;

@end

@implementation WDLocationManager

static WDLocationManager *instance;

+ (instancetype)shareInstance {
//    static WDLocationManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc] init];
    });
    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}

- (void)configLocationManager {
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    self.locationManager.locationTimeout = 5;
    self.locationManager.reGeocodeTimeout = 20;
    self.locationManager.locatingWithReGeocode = YES;
    
    [self.locationManager startUpdatingLocation];
}

- (void)geocodeSearchAds:(NSString *)address completion:(nonnull void (^)(CGFloat, CGFloat))completion {
    self.isStart = YES;
    self.searchLocationBlock = completion;
    if (!_searchManager) {
        _searchManager = [[AMapSearchAPI alloc] init];
        _searchManager.delegate = self;
    }
    AMapGeocodeSearchRequest *request = [[AMapGeocodeSearchRequest alloc] init];
    request.address = address; // 设置地址
    [self.searchManager AMapGeocodeSearch:request];
}

/// 根据经纬度获取地址
/// - Parameters:
///   - lon: lon description
///   - lat: lat description
///   - completion: completion description
- (void)geocodeSearchLon:(double)lon lat:(double)lat completion:(void(^)(NSString *ads))completion {
    self.isStart = YES;
    self.searchLocationLatLonBlock = completion;
    if (!_searchManager) {
        _searchManager = [[AMapSearchAPI alloc] init];
        _searchManager.delegate = self;
    }
    AMapGeoPoint *point = [AMapGeoPoint locationWithLatitude:lat longitude:lon];
//    AMapGeoPoint *point = [AMapGeoPoint locationWithLatitude:39.904989 longitude:116.405285];
    AMapReGeocodeSearchRequest *req = [[AMapReGeocodeSearchRequest alloc] init];
    req.location = point;
    [self.searchManager AMapReGoecodeSearch:req];
}

// AMapReGeocodeSearchRequest

/// 计算两点之间的具体
/// - Parameters:
///   - start: 开始坐标
///   - end: 结束坐标
///   - completion: completion description
- (void)getTwoPointDistance:(AMapGeoPoint *)start end:(AMapGeoPoint *)end completion:(void(^)(NSInteger distance))completion {
    self.isStart = YES;
    self.searchDistanceBlock = completion;
    AMapDistanceSearchRequest *request = [[AMapDistanceSearchRequest alloc] init];
    request.origins = @[start];
    request.destination = end;
    request.type = 1; // 驾车导航距离
    if (!_searchManager) {
        _searchManager = [[AMapSearchAPI alloc] init];
        _searchManager.delegate = self;
    }
    [self.searchManager AMapDistanceSearch:request];
}

/// 开始定位
- (void)updateLocation {
    [self.locationManager startUpdatingLocation];
}

/// 关闭定位
- (void)stopTrackLocation {
    [self.locationManager stopUpdatingLocation];
}


#pragma mark - AMapLocationManagerDelegate

- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager *)locationManager {
    [locationManager requestAlwaysAuthorization];
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode {
    self.lastLocation = location;
    CLLocationCoordinate2D coordinate = location.coordinate;
    debugLog(@"当前经纬度:lon=%f; lat=%f", coordinate.longitude, coordinate.latitude);
//    location.coordinate.latitude;
//    location.coordinate.longitude;
    if (reGeocode) {
        
        self.province = reGeocode.province;
        self.city = reGeocode.city;
        self.district = reGeocode.district;
        self.address = reGeocode.formattedAddress;
        self.adCode = reGeocode.adcode;
//        NSLog(@"address=%@-%@-%@",reGeocode.province,reGeocode.city,reGeocode.district);
        if (self.locationCityBlock) {
            self.locationCityBlock(location, self.address, self.city);
        }
        if (self.locationBlock) {
            self.locationBlock(location, self.address);
        }
        
        if (_cityBlock) {
            _cityBlock(reGeocode.city);
        }
    }
}

#pragma mark - AMapSearchDelegate

- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    debugLog(@"location-error=%@", [error localizedDescription]);
    self.searchManager.delegate = nil;
    self.searchManager = nil;
    if (self.searchLocationBlock && self.isStart) {
        self.searchLocationBlock(0, 0);
    }
    if (self.searchDistanceBlock && self.isStart) {
        self.searchDistanceBlock(0);
    }
    if (self.searchLocationLatLonBlock && self.isStart) {
        self.searchLocationLatLonBlock(@"");
    }
}

/// 获取经纬度
/// - Parameters:
///   - request: request description
///   - response: response description
- (void)onGeocodeSearchDone:(AMapGeocodeSearchRequest *)request response:(AMapGeocodeSearchResponse *)response {
    AMapGeocode *geocode = response.geocodes.firstObject;
    CGFloat latitude = 0;
    CGFloat longitude = 0;
    if (geocode) {
        latitude = geocode.location.latitude;
        longitude = geocode.location.longitude;
    }
    self.searchManager.delegate = nil;
    self.searchManager = nil;
    self.isStart = NO;
    if (self.searchLocationBlock) {
        self.searchLocationBlock(latitude, longitude);
    }
//    if (self.searchLocationLatLonBlock) {
//        
//    }
}

// 逆地理编码查询回调函数
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response {
    AMapReGeocode *geocode = response.regeocode;
    self.searchManager.delegate = nil;
    self.searchManager = nil;
    self.isStart = NO;
    if (self.searchLocationLatLonBlock) {
        self.searchLocationLatLonBlock(geocode.formattedAddress);
    }
}

/// 获取两点距离
/// - Parameters:
///   - request: request description
///   - response: response description
- (void)onDistanceSearchDone:(AMapDistanceSearchRequest *)request response:(AMapDistanceSearchResponse *)response {
    AMapDistanceResult *result = response.results.firstObject;
    NSInteger distance = 0;
    if (result) {
        distance = result.distance;
    }
    self.searchManager.delegate = nil;
    self.searchManager = nil;
    self.isStart = NO;
    if (self.searchDistanceBlock) {
        self.searchDistanceBlock(distance);
    }
}

@end






























